package com.example.utils;


import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.CodeSignature;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class VelocityUtils {

    /*****
     *
     * 字符串模板解析
     * @param object
     * @param str
     * @return
     */
    public static String process(String key, Object object, String str) {
        StringWriter writer = new StringWriter();
        Map map = new HashMap();
        Configuration configuration = new Configuration();
        configuration.setClassicCompatible(Boolean.TRUE);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        stringTemplateLoader.putTemplate("", str);
        configuration.setTemplateLoader(stringTemplateLoader);
        configuration.setDefaultEncoding("UTF-8");
        try {
            map.put(key, object);
            Template template = configuration.getTemplate("");
            template.process(map, writer);
        } catch (Exception e) {
            return str;
        }
        return writer.toString();
    }


    /*****
     *
     * aop处理参数
     * @param joinPoint
     * @param str
     * @return
     */
    public static String process(ProceedingJoinPoint joinPoint, String str) {
        Map<String, Object> map = new HashMap<String, Object>();
        Object[] args = joinPoint.getArgs();
        String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
        for (int i = 0; i < paramNames.length; i++) {
            map.put(paramNames[i], args[i]);
        }
        StringWriter writer = new StringWriter();
        Configuration configuration = new Configuration();
        configuration.setClassicCompatible(Boolean.TRUE);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        stringTemplateLoader.putTemplate("", str);
        configuration.setTemplateLoader(stringTemplateLoader);
        configuration.setDefaultEncoding("UTF-8");
        try {
            Template template = configuration.getTemplate("");
            template.process(map, writer);
        } catch (Exception e) {
            return str;
        }
        return writer.toString();
    }

}